<template>
  <div class="tag-list">
    <template v-if="formatList.length === 1">
      <el-button type="text" icon="el-icon-view" style="margin-left: 5px" @click="showDetailDialog = true">查看</el-button>
      <el-button v-if="isEditing" type="text" style="margin-left: 5px" @click="handleCreate">新增</el-button>
    </template>

    <template v-if="!formatList.length">
      <el-button v-if="isEditing" type="text" style="margin-left: 5px" @click="handleCreate">新增</el-button>
    </template>

    <template v-if="formatList.length > 1">
      <el-button type="text" icon="el-icon-view" @click="showDetailDialog = true">查看</el-button>
      <el-button v-if="isEditing" type="text" style="margin-left: 5px" @click="handleCreate">新增</el-button>
    </template>

    <!-- 详情弹窗 -->
    <el-dialog
      title="详细信息"
      :visible.sync="showDetailDialog"
      width="500px"
      append-to-body
    >
      <div class="detail-list">
        <div v-for="(item, index) in formatList" :key="index" class="detail-item">
          <div class="item-header">
            <div class="header-content">
              <div v-if="item.logo" class="avatar">
                <img :src="item.logo" alt="logo">
              </div>
              <div v-else class="avatar">{{ item.name?.[0] || '-' }}</div>
              <span class="name">{{ item.name }}</span>
            </div>
            <div v-if="isEditing" class="header-actions">
              <el-button type="text" @click="handleEdit(item, index)">编辑</el-button>
              <el-button type="text" style="color: #F56C6C" @click="handleDelete(index)">删除</el-button>
            </div>
          </div>
          <div class="position-list">
            <el-tag v-for="(pos, posIndex) in item.position" :key="posIndex" size="small" style="margin-right: 5px;">{{ pos }}</el-tag>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      append-to-body
    >
      <div class="dialog-content">
        <el-form
          label-width="80px"
          label-position="left"
        >
          <el-form-item label="工作单位">
            <el-select
              v-model="currentCompany"
              placeholder="请选择工作单位"
              style="width: 100%"
            >
              <el-option
                v-for="item in companyList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-button type="text" style="margin-top: 5px" @click="createCompanyVisible = true">没有你的工作单位？点击创建</el-button>
          </el-form-item>

          <el-form-item label="职位">
            <el-input
              v-model="positions"
              type="textarea"
              :rows="3"
              placeholder="请输入职位"
            />
            <div class="tip-text">提示：请输入职位，多个职位请使用"，"隔开,最多添加2个职位，每个职位字数不超过6个</div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 创建公司弹窗 -->
    <CompanyCardCreate
      :visible.sync="createCompanyVisible"
      @submit="handleCompanyCreate"
    />
  </div>
</template>
<script>
import { getCompanyCardList, addCompanyCard } from '@/api/personnel'
import CompanyCardCreate from './CompanyCardCreate.vue'
import { deepClone } from '@/utils'

export default {
  name: '',
  components: {
    CompanyCardCreate
  },
  props: {
    list: {
      type: Array,
      default: () => {
        return []
      }
    },
    isEditing: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      showDetailDialog: false,
      companyList: [],
      createCompanyVisible: false,
      currentCompany: null,
      positions: [],
      editingItem: null
    }
  },
  computed: {
    formatList() {
      return this.list.every(item => typeof item === 'string') ? [] : this.list
    },
    dialogTitle() {
      return this.editingItem ? '编辑职位' : '新增职位'
    }
  },
  created() {
    this.fetchCompanyList()
  },
  methods: {
    async fetchCompanyList() {
      try {
        const res = await getCompanyCardList()
        this.companyList = res.data || []
      } catch (error) {
        console.error('获取公司列表失败：', error)
      }
    },
    handleEdit(item, index) {
      this.editingItem = deepClone({ ...item, index })
      this.currentCompany = item.id
      this.positions = item.position?.join('，') || ''
      this.dialogVisible = true
    },
    async handleCompanyCreate(companyData) {
      try {
        const res = await addCompanyCard(companyData)
        await this.fetchCompanyList()
        this.createCompanyVisible = false
        this.$message.success('创建成功')
      } catch (error) {
        console.error('创建公司失败：', error)
        this.$message.error(error?.response?.data?.message || '创建失败')
      }
    },
    handleConfirm() {
      if (!this.currentCompany) {
        this.$message.warning('请选择工作单位')
        return
      }
      if (this.currentCompany === 'create') {
        this.createCompanyVisible = true
        return
      }

      if (!this.editingItem) {
        // 检查工作单位是否已存在
        const isCompanyExist = this.formatList.some(item => item.id === this.currentCompany)
        if (isCompanyExist) {
          this.$message.warning('该工作单位已添加，请勿重复添加')
          return
        }
      } else {
        const isCompanyExist = this.formatList.some(item => item.id === this.currentCompany)
        if (this.currentCompany !== this.editingItem.id && isCompanyExist) {
          this.$message.warning('该工作单位已添加，请勿重复添加')
          return
        }
      }

      const positionList = this.positions
        .split(/[,，]/) // 同时处理中英文逗号
        .map(item => item.trim()) // 去除空格
        .filter(item => item) // 过滤空字符串

      // 检查职位数量
      if (positionList.length > 2) {
        this.$message.warning('最多只能添加两个职位')
        return
      }

      // 检查每个职位的字符长度
      const invalidPosition = positionList.find(pos => pos.length > 6)
      if (invalidPosition) {
        this.$message.warning(`职位"${invalidPosition}"超过6个字符`)
        return
      }

      // 从companyList中获取完整的公司信息
      const company = this.companyList.find(item => item.id === this.currentCompany)
      if (!company) {
        this.$message.warning('未找到对应的公司信息')
        return
      }

      const newCompanyData = {
        id: company.id,
        name: company.name,
        logo: company.logo,
        position: positionList
      }

      let newList
      if (this.editingItem) {
        // 编辑模式：更新现有数据
        newList = [...this.formatList]
        newList[this.editingItem.index] = newCompanyData
      } else {
        // 新增模式：添加新数据
        newList = [...this.formatList, newCompanyData]
      }

      this.$emit('update:list', newList)
      this.dialogVisible = false
    },

    handleCreate() {
      this.editingItem = null
      this.currentCompany = ''
      this.positions = ''
      this.dialogVisible = true
    },

    handleDelete(index) {
      const list = [...this.formatList]

      list.splice(index, 1)
      console.log('list --------->', list)
      this.$emit('update:list', list)
    }
  }
}
</script>
<style lang="scss" scoped>
.tag-list {
  display: inline-flex;
  align-items: center;
}

.tag-content {
  display: flex;
  align-items: center;
  gap: 5px;
}

.avatar {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  overflow: hidden;
  color: #fff;

  &:not(:has(img)) {
    background: #409EFF;
  }

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.detail-list {
  .detail-item {
    margin-bottom: 20px;
    padding: 10px;
    border-radius: 4px;
    border: 1px solid #EBEEF5;

    &:last-child {
      margin-bottom: 0;
    }

    .item-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;

      .header-content {
        display: flex;
        align-items: center;
      }

      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background-color: #409EFF;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
        font-size: 16px;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .name {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }

      .header-actions {
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }

    .position-list {
      margin-top: 8px;
    }
  }
}

.dialog-content {
  .tip-text {
    color: #909399;
    font-size: 12px;
    margin-top: 5px;
    line-height: 20px;
  }
}
</style>
